from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import os

from .ocr_processor import InvoiceOCR,InvoiceExtractor,TemplateOCR
from .invoice_ocr import AdaptiveInvoiceOCR

app = FastAPI(title="发票识别服务")

# CORS配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 初始化OCR引擎
# ocr_engine = TemplateOCR()
ocr_engine = AdaptiveInvoiceOCR(use_gpu=False)

@app.post("/ocr/invoice")
async def invoice_ocr(file: UploadFile = File(...)):
    # 保存临时文件
    file_path = f"/tmp/{file.filename}"
    with open(file_path, "wb") as f:
        f.write(await file.read())
    # OCR 识别
    # texts = ocr_engine.extract_text(file_path)

    # 结构化提取
    # extractor = InvoiceExtractor(texts)
    # result = extractor.extract()

    # return {"success": True, "data": result}
    # 执行结构化 OCR
    # result = ocr_engine.extract_from_image(file_path)

    result = ocr_engine.extract_from_image(file_path)
    print(f"识别结果为：{result}")
    return {"success": True, "data": result}

@app.post("/api/v1/invoice/recognize")
async def recognize_invoice(image: UploadFile = File(...)):
    """
    发票识别接口
    - 参数: 图片文件
    - 返回: 发票结构化信息
    """
    # 检查文件类型
    if not image.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="文件必须是图片格式")
    
    # 读取图片
    contents = await image.read()
    if len(contents) > 10 * 1024 * 1024:  # 10MB限制
        raise HTTPException(status_code=400, detail="图片大小不能超过10MB")
    
    # 转换为base64
    import base64
    base64_image = base64.b64encode(contents).decode('utf-8')
    
    # 执行识别
    result = ocr_engine.recognize(base64_image)
    
    return result

@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy", "service": "invoice-ocr"}